package LC;

import java.util.ArrayList;
import java.util.Stack;

/**
 * https://leetcode.com/problems/binary-tree-preorder-traversal/description/
 * Given a binary tree, return the preorder traversal of its nodes' values.
 * For example:
 * Given binary tree {1,#,2,3},
 * 1
 * \
 * 2
 * /
 * 3
 * return [1,2,3].
 * Note: Recursive solution is trivial, could you do it iteratively?
 */
public class LC_144_BinaryTreePreorderTraversal_Recur_BinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        ArrayList<Integer> res = Solution.preorderTraversal(root);
        System.out.println(res);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root != null) {
                result.add(root.val);
                result.addAll(preorderTraversal(root.left));
                result.addAll(preorderTraversal(root.right));
            }
            return result;
        }
    }

    static class Solution_2 {
        static ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root == null) return result;
            Stack<TreeNode> nodeStack = new Stack<>();
            nodeStack.push(root);
            while (!nodeStack.empty()) {
                TreeNode node = nodeStack.pop();
                result.add(node.val);
                if (node.right != null) nodeStack.push(node.right);
                if (node.left != null) nodeStack.push(node.left);
            }
            return result;
        }
    }
}